package pers.vic.test.config.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import pers.vic.test.json.jackson.XssStringJsonSerializer;

/**
 * 描述:对所有转json对象进行Xss转义， 可以在字段是上使用@JsonSerialize(using = XssStringJsonSerializer.class)，此处注册为全局，则不再需要单独处理
 * @author Vic.xu
 * @date 2022-03-21 11:38
 */
@Configuration
public class JsonConfig {

    private Logger logger = LoggerFactory.getLogger(JsonConfig.class);


    /**
     *
     * @param builder
     * @return
     */
    @Bean
    @Primary
    public ObjectMapper xssObjectMapper(Jackson2ObjectMapperBuilder builder) {
        logger.info("register xssObjectMapper");
        //解析器
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //注册xss解析器
        SimpleModule xssModule = new SimpleModule("XssStringJsonSerializer");
        xssModule.addSerializer(String.class, new XssStringJsonSerializer());
        objectMapper.registerModule(xssModule);
        //返回
        return objectMapper;
    }
}
